<template>
  <div style="background-color: #fff; padding: 20px">
    <div class="flex-space-between-item">
      <div class="flex-start-item">
        <div class="item flex-start-item">
          <p>菜品名称：</p>
          <el-input placeholder="请输入内容" class="input-form" v-model="searchText" id="dish-searcher"/>
        </div>
        <div class="item flex-start-item">
          <p>售卖状态：</p>
          <select placeholder="请选择" v-model="saleState" class="input-form" id="dish-selector">
            <option label="全部" value="all"></option>
            <option label="起售" value="起售"></option>
            <option label="停售" value="停售"></option>
          </select>
        </div>
      </div>
      <div class="flex-start-item">
        <el-button type="danger" link @click="delDishes">批量删除</el-button>
        <el-button type="primary" @click="createDialogVisible = true">新增菜品</el-button>
      </div>
    </div>
    <div style="margin-top: 20px">
      <el-table
        :data="filteredDishes"
        style="width: 100%"
        @selection-change="handleSelection"
        :header-cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column prop="date" label="Date" width="50" type="selection" />
        <el-table-column label="图片" width="80" align="center">
          <!-- <img src=""> -->
          <template #default="scope">
            <img style="width: 40px" :src="scope.row.image" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" width="150" align="center" />
        <el-table-column prop="price" label="售价" width="100" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center" />
        <el-table-column prop="updateTime" label="最后操作时间" width="275" align="center" />
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button-group>
              <el-button
                plain
                size="small"
                @click="(updateDialogVisible = true), Object.assign(formData, scope.row)"
                >修改</el-button
              >
              <el-button plain size="small" @click="delDish(scope.row.id)">删除</el-button>
              <el-button
              :type="scope.row.status==='起售' ? 'danger' : 'success'"
                plain
                size="small"
                @click="setDishStatus(scope.row.status, scope.row.id)"
                >{{ scope.row.status === '起售' ? '停售' : '起售' }}</el-button
              >
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;margin-top: 10px;" class="flex-center-item">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper" :total="totalDishes" @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
  <el-dialog v-model="createDialogVisible" title="创建菜品" width="80%">
    <el-form :model="formData" label-width="100px" style="padding: 20px">
      <el-form-item label="菜品名称：" prop="oldPwd"
        ><el-input v-model="formData.name"></el-input
      ></el-form-item>
      <el-form-item label="菜品价格：" prop="newPwd"
        ><el-input v-model="formData.price"></el-input
      ></el-form-item>
      <el-form-item label="菜品描述：" prop="newPwd"
        ><el-input v-model="formData.description"></el-input
      ></el-form-item>
    </el-form>
    <div class="flex-end-item">
      <el-button @click="createDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="createDish()">确定</el-button>
    </div>
  </el-dialog>
  <el-dialog v-model="updateDialogVisible" title="更新菜品" width="80%">
    <el-form :model="formData" label-width="100px" style="padding: 20px">
      <el-form-item label="菜品名称：" prop="oldPwd"
        ><el-input v-model="formData.name"></el-input
      ></el-form-item>
      <el-form-item label="菜品价格：" prop="newPwd"
        ><el-input v-model="formData.price"></el-input
      ></el-form-item>
      <el-form-item label="菜品描述：" prop="newPwd"
        ><el-input v-model="formData.description"></el-input
      ></el-form-item>
    </el-form>
    <div class="flex-end-item">
      <el-button @click="updateDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="updateDish()">确定</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed,watch } from 'vue'
const totalDishes=ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
watch(pageSize, handleCurrentChange)
function handleCurrentChange() {
  dishes.value = []
  fetch(`/api/admin/dish/page?page=${currentPage.value}&pageSize=${pageSize.value}`, {
  headers: headers
})
  .then((res) => res.json())
  .then((data) => {
    if (data.code === 1) {
      data.data.records.forEach((item) => {
        dishes.value.push({
          id: item.id,
          name: item.name,
          price: item.price,
          image: item.image,
          description: item.description,
          status: item.status === 1 ? '起售' : '停售',
          createTime: item.updateTime,
          updateTime: item.updateTime,
          checked: false
        })
      })
    }
  })
}


const dishes = ref([])
const createDialogVisible = ref(false)
const updateDialogVisible = ref(false)
const formData = reactive({
  categoryId: 12,
  description: '',
  image:
    'https://sky-take-out-2907.oss-cn-beijing.aliyuncs.com/2fb56d78-34ec-48c9-bfcd-5f5fd923a02b.jpg',
  name: '',
  price: 0
})
const headers = new Headers({
  application: 'json',
  Authorization: sessionStorage.getItem('token')!,
  token: sessionStorage.getItem('token')!
})
fetch('/api/admin/dish/page?page=1&pageSize=10', {
  headers: headers
})
  .then((res) => res.json())
  .then((data) => {
    if (data.code === 1) {
      totalDishes.value = data.data.total
      data.data.records.forEach((item) => {
        dishes.value.push({
          id: item.id,
          name: item.name,
          price: item.price,
          image: item.image,
          description: item.description,
          status: item.status === 1 ? '起售' : '停售',
          createTime: item.updateTime,
          updateTime: item.updateTime,
          checked: false
        })
      })
    }
  })

let selectedItems = []
function handleSelection(val) {
  selectedItems = []
  val.forEach((item) => {
    selectedItems.push(item.id)
  })
}

const searchText = ref('')
const categoryFilter = ref(1)
const saleState = ref('all')

const filteredDishes = computed(() => {
  return dishes.value.filter((dish) => {
    if (searchText.value != '') {
      if (!dish.name.includes(searchText.value)) return false
    }
    if (saleState.value != 'all') {
      if (dish.status != saleState.value) return false
    }
    return true
  })
})
function delDish(id) {
  fetch(`/api/admin/dish?ids=${id}`, {
    headers: headers,
    method: 'DELETE'
  })
    .then((res) => res.json())
    .then((data) => {
      console.log(data)
      if (data.code === 1) {
        dishes.value = dishes.value.filter((item) => id !== item.id)
      }
    })
}
function delDishes() {
  fetch(`/api/admin/dish?ids=${String(selectedItems)}`, {
    headers: headers,
    method: 'DELETE'
  })
    .then((res) => res.json())
    .then((data) => {
      console.log(data)
      if (data.code === 1) {
        dishes.value = dishes.value.filter((item) => !selectedItems.includes(item.id))
      }
    })
}
function setDishStatus(status, id) {
  fetch(`/api/admin/dish/status/${status === '起售' ? 0 : 1}?id=${id}`, {
    headers: headers,
    method: 'POST'
  })
    .then((res) => res.json())
    .then((data) => {
      console.log(data)
      if (data.code === 1) {
        const dish = dishes.value.findIndex((item) => item.id === id)
        dishes.value[dish].status = status === '起售' ? '停售' : '起售'
      }
    })
}
function createDish() {
  fetch(`/api/admin/dish`, {
    headers: new Headers({
      application: 'json',
      Authorization: sessionStorage.getItem('token')!,
      token: sessionStorage.getItem('token')!,
      'Content-Type': 'application/json'
    }),
    method: 'POST',
    body: JSON.stringify(formData)
  }).then(()=>{
    createDialogVisible.value=false
    handleCurrentChange()
  })
  
}
function updateDish() {
  delete formData.status
  fetch(`/api/admin/dish`, {
    headers: new Headers({
      application: 'json',
      Authorization: sessionStorage.getItem('token')!,
      token: sessionStorage.getItem('token')!,
      'Content-Type': 'application/json'
    }),
    method: 'PUT',
    body: JSON.stringify(formData)
  }).then(()=>{
    updateDialogVisible.value=false
    handleCurrentChange()
  })
}
</script>

<style scoped>
@import '@/assets/common.css';

p {
  text-wrap: nowrap;
}

.item {
  margin-right: 10px;
}

.input-form {
  width: 150px;
}
</style>
